package com.smproject.enums.checks;


import cn.hutool.core.util.StrUtil;
import com.smproject.exception.ModelVailException;
import lombok.val;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * @author hu.liang
 * @Date 2019/6/27 0027
 */
public class VailTelephoneValidator implements ConstraintValidator<VailTelephone, Object> {

   private int telephoneType = 1;
   private String message = "号码输入有误!";
   private boolean require;

   /**
    * 校验的方法名
    */
   private String methodName = "validation";


   @Override
   public void initialize(VailTelephone constraint) {
      this.telephoneType = constraint.telephoneType();
      this.message = constraint.message();
      this.require = constraint.require();
   }

   @Override
   public boolean isValid(Object val, ConstraintValidatorContext context) {
      //判断是否是必填的
      if(this.require){
         if(Objects.isNull(val)){
            return false;
         }
      }
      try {
         //手机号
         boolean flag = PhoneRegex.validation(telephoneType, val.toString());
         if(!flag){
            throw new ModelVailException(this.message);
         }
         return true;
      }catch (Exception e){
         e.printStackTrace();
      }
      return false;
   }
}
